package com.cy.aircompressor.main.welcome.viewmodel;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.MediatorLiveData;
import androidx.lifecycle.Observer;

import com.cy.aircompressor.api.RepositoryImpl;
import com.cy.aircompressor.entity.system.UserInfo;
import com.cy.aircompressor.utils.MD5;
import com.drug.lib.util.DLog;
import com.net.model.base.Resource;
import com.net.model.viewmodel.BaseViewModel;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

/**
 * 版权：周和权 版权所有
 *
 * @author zhouhequan
 * 版本：1.0
 * 创建日期：2021/11/12 or 23:27
 * 描述：---
 */
public class WelcomeViewModel extends BaseViewModel<RepositoryImpl> {
    private MediatorLiveData<Resource<String>> loginObservable;
    private MediatorLiveData<Resource<UserInfo>> userInfoObservable;

    public WelcomeViewModel(@NonNull Application application) {
        super(application);
        bindBaseModel(RepositoryImpl.get());
        loginObservable = new MediatorLiveData<>();
        userInfoObservable = new MediatorLiveData<>();
    }

    public void login(String username, String pwd) {
        Map<String, Object> body = new HashMap<>();
        body.put("account", username);
        body.put("pwd", MD5.encrypt2ToMD5(pwd));
        DLog.d("password:" + MD5.encrypt2ToMD5(pwd));
        loginObservable.addSource(baseModel.login(body), new Observer<Resource<String>>() {
            @Override
            public void onChanged(Resource<String> authBeanResource) {
                loginObservable.setValue(authBeanResource);
            }
        });
    }

    public void currentUserInfo() {
        userInfoObservable.addSource(getRepository().currentUserInfo(), new Observer<Resource<UserInfo>>() {
            @Override
            public void onChanged(Resource<UserInfo> userInfoResource) {
                userInfoObservable.setValue(userInfoResource);
            }
        });
    }

    public MediatorLiveData<Resource<String>> getLoginObservable() {
        return loginObservable;
    }

    public MediatorLiveData<Resource<UserInfo>> getUserInfoObservable() {
        return userInfoObservable;
    }


}
